import React, {useEffect, useState} from 'react'
import {Input, Button, Modal, Row, Col, Select, message, Form} from 'antd'
import {connect} from 'umi'
import SelectUserModal from "@/pages/components/SelectUserModal"
import {getAllInsuranceList, saveOrUpdateEmployeeSecurity} from '../../service'
import {PlusOutlined} from '@ant-design/icons'
import {employeeStatusList, insuranceStatusList} from "@/utils/constant";
import ProTable, {ProColumns, ActionType} from '@ant-design/pro-table'
import moment from 'moment'

const {Option} = Select;
const FormItem = Form.Item;

const CreateForm = (props) => {
  const {onCancel, visible, current, onSubmit} = props;
  const [loading, setLoading] = useState(false);
  const [form] = Form.useForm();
  const [userModalVisible, setUserModalVisible] = useState(false);
  const [securityUserItems, setSecurityUserItems] = useState([]);
  const [schemeList, setSchemeList] = useState([]);

  const reloadTable = () => {

  };

  useEffect(() => {
    if (visible) {
      getAllInsuranceList().then(res => setSchemeList(res));
      if (current.length>0){
        setLoading(true);
        form.setFieldsValue({companyId: current[0].companyId, companyName: current[0].current});
        setSecurityUserItems(current);
        setLoading(false);
      }
    }
  }, [visible]);

  const onFormCancel = () => {
    setSecurityUserItems([]);
    form.resetFields();
    onCancel();
  };

  const confirmSelectedUsers = (values) => {
    let needValues = [];
    values.forEach(item => {
      if (securityUserItems.filter(fItem => fItem.oid.toString() === item.oid.toString()).length < 1)
        needValues.push({
          oid: item.oid,
          code: item.code,
          name: item.name,
          orgname:item.orgname,
          unitname: item.unitname,
          jobname: item.jobname,
          employeestatus: item.employeestatus,
          hiredate: item.hiredate,
          insuranceId: current.length > 0 ? current[0].id : null
        })
    });
    setSecurityUserItems([...securityUserItems, ...needValues]);
    setUserModalVisible(false);
  };

  const selectOnChange = (value, option) => {
    form.setFieldsValue({companyName: option.lable.name});
  };

  const onFormSubmit = async () => {
    const fieldValues = await form.validateFields();
    if (securityUserItems.length < 1){
      message.error('操作失败，请选择员工后再进行此操作！');
      return
    }
    onSubmit(securityUserItems.map(item => ({...item, ...fieldValues, status: 1})));
    form.resetFields();
  };

  let columns = [
    {
      title: '序号',
      dataIndex: 'index',
      render: (text, record, index) => `${index + 1}`,
    },
    {
      title: '工号',
      dataIndex: 'code',
    },
    {
      title: '姓名',
      dataIndex: 'name',
    },
    {
      title: '公司',
      dataIndex: 'orgname',
    },
    {
      title: '部门',
      dataIndex: 'unitname',
    },
    {
      title: '岗位',
      dataIndex: 'jobname',
    },
    {
      title: '状态',
      dataIndex: 'employeestatus',
      render: (text, record) => {
        return text !== '-' ? employeeStatusList.find(item => (item.value === `${text}`))?.label : ''
      }
    },
    {
      title: '入职时间',
      dataIndex: 'hiredate',
      render: (text) => text !== '-' && moment(text).format('YYYY-MM-DD')
    },
  ];

  const renderFooter = () => <>
    <Button type="primary" onClick={() => onFormCancel()}>关闭</Button>
    <Button type="primary" onClick={() => onFormSubmit()}>提交</Button>
  </>;

  return (
    <Modal
      title='方案人员配置'
      width={'90%'}
      destroyOnClose
      visible={visible}
      footer={renderFooter()}
      onOk={onFormCancel}
      onCancel={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form form={form}>
        <Row gutter={24}>
          <Col span={0}>
            <FormItem name="companyName" label="被保险单位名称">
              <Input type={"text"}/>
            </FormItem>
          </Col>
          <Col span={8}>
            <FormItem name="insuranceId" label="雇主责任险方案" rules={[{required: true, message: '雇主责任险方案不能为空'}]}>
              <Select className='widthStyle' placeholder="请选择方案" getPopupContainer={triggerNode => triggerNode.parentNode}
                        onChange={selectOnChange}>
                {schemeList.map((item, index) => {
                  return (
                    <Option value={item.id} key={index} lable={item}>
                      {item.companyName}
                    </Option>
                  )
                })}
              </Select>
            </FormItem>
          </Col>
          <Col span={24}>
            <ProTable
              rowKey="id"
              loading={loading}
              toolBarRender={false}
              columns={columns}
              dataSource={securityUserItems}
              search={false}
              pagination={false}
            />
          </Col>
          {
            !current.length &&
            <Col span={24}>
              <Button style={{width: '100%', marginBottom: 8}} type="dashed" onClick={() => setUserModalVisible(true)}>
                <PlusOutlined/>
                新增成员
              </Button>
            </Col>
          }
        </Row>
      </Form>
      <SelectUserModal
        isDismiss={true}
        selectType={1}
        visible={userModalVisible}
        handleOk={confirmSelectedUsers}
        handleCancel={() => setUserModalVisible(false)}
      />
    </Modal>
  )
};


export default connect(({}) => ({}))(CreateForm)
